package com.bw.image.imageUtils.glide

import android.content.Context
import android.os.Environment
import com.bumptech.glide.Glide
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.Registry
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory
import com.bumptech.glide.load.engine.cache.LruResourceCache
import com.bumptech.glide.load.engine.cache.MemorySizeCalculator
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.module.AppGlideModule
import okhttp3.Cache
import okhttp3.OkHttpClient
import java.io.File
import java.io.InputStream

class CustomGlideModule:AppGlideModule () {
    /**
     * 自定义Glide 内存和磁盘缓存
     */
    override fun applyOptions(context: Context, builder: GlideBuilder) {


        //计算使用多大的内存空间
        val glideMemorySize = MemorySizeCalculator.Builder(context).build().memoryCacheSize/6L
        //设置内存大小（默认为当前APP内存的1/8）
        builder.setMemoryCache(LruResourceCache(glideMemorySize))

        //设置磁盘大小（默认250M）
        builder.setDiskCache(InternalCacheDiskCacheFactory(context,"glide_disk_cache",300*1024*1024))
    }


    /**
     * 自定义网络缓存大小
     * Glide 网络采用OKHttp实现
     */
    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {

            try {
                val builder = OkHttpClient.Builder()
                //先考虑外部SDK,如果没有在考虑内存SD卡
                val externalDir = Environment.getExternalStorageDirectory()
                var cacheDir = if (externalDir.exists()){
                    "${externalDir.absolutePath}/glideCache" //外置SD卡
                }else{
                    "${context.externalCacheDir?.absolutePath}/glideCache" //内置SD卡
                }

                val cacheFile = File(cacheDir)

                //计算一下缓存大小
                var cacheSize = if (externalDir.exists()&&externalDir.totalSpace>8L){
                    externalDir.totalSpace/8L
                }else{
                    context.externalCacheDir?.totalSpace?.div(8L) ?: (10 * 1024 * 1024)
                }


                val networkCache = Cache(cacheFile,cacheSize)
                //设置网络缓存目录
                builder.cache(networkCache)

                val newOkHttpClient = builder.build()
                //替换OKHttp客户端
                registry.replace(GlideUrl::class.java, InputStream::class.java, OkHttpUrlLoader.Factory())

            }catch (e:Exception){
                e.printStackTrace()
            }
        }
}